package moh.s2.s2dao.impl;

import java.util.List;

import moh.s2.s2dao.PropertiesDAO;
import moh.s2.s2entity.Properties;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

//@Repository
public class PropertiesDAOImpl implements PropertiesDAO {
	// @Autowired
	private SessionFactory sessionFactory;

	@Transactional
	public void add(Properties properties) throws Exception {
		getSession().merge(properties);

	}

	@Transactional
	public void update(Properties properties) throws Exception {
		getSession().update(properties);

	}

	@Transactional
	public void delete(Properties properties) throws Exception {
		getSession().delete(properties);

	}

	@Transactional
	public List<Properties> list() throws Exception {
		org.hibernate.Query q = getSession().createQuery("from Properties");
		return (List<Properties>) q.list();
	}

	@Transactional
	public Properties findByKey(String key) throws Exception {
		org.hibernate.Query q = getSession().createQuery("from Properties where propertyKey=:val").setParameter("val", key);
		return (Properties) q.list().get(0);
	}

	@Transactional
	public Properties findByValue(String value) throws Exception {
		org.hibernate.Query q = getSession().createQuery("from Properties where propertyVale=:val").setParameter("val", value);
		return (Properties) q.list().get(0);
	}

	private Session getSession() {
		Session sess = getSessionFactory().getCurrentSession();
		if (sess == null) {
			sess = getSessionFactory().openSession();
		}
		return sess;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
